<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <div class="container">
          <el-form size="small" label-width="120px" :inline="true">
            <el-form-item label="服务人员：">
              <el-select v-model="tableFrom.staff_id" placeholder="请选择" class="filter-item selWidth" clearable
                @change="getList(1)">
                <el-option v-for="item in staffList" :key="item.staff_id" :label="item.name"
                  :value="item.staff_id" />
              </el-select>
            </el-form-item>
            <el-form-item label="服务项目：">
              <el-select v-model="tableFrom.service_id" placeholder="请选择" class="filter-item selWidth" clearable
                @change="getList(1)">
                <el-option v-for="item in serviceList" :key="item.id" :label="item.name"
                  :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="排班日期：">
              <el-date-picker
                v-model="tableFrom.date"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                class="selWidth"
                clearable
                @change="getList(1)"
              ></el-date-picker>
            </el-form-item>
          </el-form>
        </div>
        <div class="header-buttons">
          <el-button size="small" type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">批量删除</el-button>
          <el-button size="small" type="primary" @click="openAddModal">添加排班</el-button>
        </div>
      </div>
      <el-table v-loading="listLoading" :data="tableData.data" style="width: 100%" size="mini"
        :row-class-name="tableRowClassName" @rowclick.stop="closeEdit" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" min-width="50" />
        <el-table-column prop="staff_name" label="服务人员" min-width="120" />
        <el-table-column prop="service_name" label="服务项目" min-width="120" />
        <el-table-column label="排班日期" min-width="120">
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.date) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="时间段" min-width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.start_time }} - {{ scope.row.end_time }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="可预约人数" min-width="100" />
        <el-table-column prop="create_time" label="创建时间" min-width="150" />
        <el-table-column label="操作" min-width="150" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" class="mr10" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination :page-sizes="[20, 40, 60, 80]" :page-size="tableFrom.limit" :current-page="tableFrom.page"
          layout="total, sizes, prev, pager, next, jumper" :total="tableData.total" @size-change="handleSizeChange"
          @current-change="pageChange" />
      </div>
    </el-card>

    <!-- 添加/编辑排班弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" :before-close="handleDialogClose">
      <el-form :model="formData" :rules="rules" ref="formValidate" label-width="100px">
        <el-form-item label="服务人员" prop="staff_id">
          <el-select v-model="formData.staff_id" placeholder="请选择服务人员" style="width: 100%">
            <el-option v-for="item in staffList" :key="item.staff_id" :label="item.name" :value="item.staff_id"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="服务项目" prop="service_id">
          <el-select v-model="formData.service_id" placeholder="请选择服务项目" style="width: 100%">
            <el-option v-for="item in serviceList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="排班日期" prop="date">
          <el-date-picker
            v-model="formData.date"
            type="date"
            placeholder="请选择日期"
            style="width: 100%"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        
        <!-- 批量创建选项 -->
        <el-form-item label="批量创建" v-if="!formData.id">
          <el-switch v-model="batchMode" @change="handleBatchModeChange"></el-switch>
        </el-form-item>
        
        <!-- 修改星期几选择部分 -->
        <template v-if="batchMode && !formData.id">
          <el-form-item label="选择星期" prop="week_days">
          <el-checkbox-group v-model="formData.week_days">
            <el-checkbox :label="1" :key="1">周一</el-checkbox>
            <el-checkbox :label="2" :key="2">周二</el-checkbox>
            <el-checkbox :label="3" :key="3">周三</el-checkbox>
            <el-checkbox :label="4" :key="4">周四</el-checkbox>
            <el-checkbox :label="5" :key="5">周五</el-checkbox>
            <el-checkbox :label="6" :key="6">周六</el-checkbox>
            <el-checkbox :label="7" :key="7">周日</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
          
          <el-form-item label="结束日期" prop="end_date">
            <el-date-picker
              v-model="formData.end_date"
              type="date"
              placeholder="请选择结束日期"
              style="width: 100%"
              value-format="yyyy-MM-dd"
              :picker-options="{
                disabledDate: (time) => {
                  return formData.date && time.getTime() < new Date(formData.date).getTime();
                }
              }"
            ></el-date-picker>
          </el-form-item>
        </template>
        
        <el-form-item label="开始时间" prop="start_time">
          <el-time-picker
            v-model="formData.start_time"
            format="HH:mm"
            placeholder="请选择开始时间"
            style="width: 100%"
            value-format="HH:mm"
          ></el-time-picker>
        </el-form-item>
        
        <el-form-item label="结束时间" prop="end_time">
          <el-time-picker
            v-model="formData.end_time"
            format="HH:mm"
            placeholder="请选择结束时间"
            style="width: 100%"
            value-format="HH:mm"
          ></el-time-picker>
        </el-form-item>
        
        <el-form-item label="可预约人数" prop="num">
          <el-input-number
            v-model="formData.num"
            :min="1"
            :max="100"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleDialogClose">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
import { getStaffList, getServiceList, getArrangeList, saveArrange, updateArrange, deleteArrange, batchDeleteArrange } from '@/api/reservationArrange'
import { roterPre } from '@/settings'

export default {
  name: 'ReservationArrange',
  components: {},
 
  data() {
    return {
      roterPre: roterPre,
      listLoading: true,
      submitLoading: false,
      dialogVisible: false,
      dialogTitle: '添加排班',
      tableData: {
        data: [],
        total: 0
      },
      tableFrom: {
        page: 1,
        limit: 20,
        staff_id: '',
        service_id: '',
        date: ''
      },
      staffList: [], // 服务人员列表
      serviceList: [], // 服务项目列表
      tabClickIndex: '',
      batchMode: false, // 批量创建模式
      selectedRows: [], // 修正：将selectedRows移到这里
      formData: {
        id: 0,
        staff_id: '',
        service_id: '',
        start_time: '',
        end_time: '',
        num: 1,
        date: '',
        arrage_time_list: '',
        week_days: [], // 选择的星期几
        end_date: '' // 结束日期
    
      },
      rules: {
        staff_id: [
          { required: true, message: '请选择服务人员', trigger: 'change' }
        ],
        service_id: [
          { required: true, message: '请选择服务项目', trigger: 'change' }
        ],
        date: [
          { required: true, message: '请选择排班日期', trigger: 'change' }
        ],
        start_time: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        end_time: [
          { required: true, message: '请选择结束时间', trigger: 'change' }
        ],
        num: [
          { required: true, message: '请输入可预约人数', trigger: 'blur' }
        ],
        week_days: [
          { type: 'array', required: true, message: '请至少选择一天', trigger: 'change' }
        ],
        end_date: [
          { required: true, message: '请选择结束日期', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    this.getStaffList()
    this.getServiceList()
    this.getList(1)
  },
  methods: {
    // 获取服务人员列表
    getStaffList() {
      getStaffList().then(res => {
        this.staffList = res.data || []
      }).catch(res => {
        this.$message.error(res.message || '获取服务人员失败')
      })
    },
    
    // 获取服务项目列表
    getServiceList() {
      getServiceList().then(res => {
        this.serviceList = res.data || []
      }).catch(res => {
        this.$message.error(res.message || '获取服务项目失败')
      })
    },
    
    // 修复获取排班列表方法
    getList(num) {
      this.listLoading = true
      this.tableFrom.page = num || this.tableFrom.page
      
      // 创建一个新的查询对象，避免修改原始对象
      const params = { ...this.tableFrom }
      
      getArrangeList(params)
        .then(res => {
          this.tableData.data = res.data.list || []
          this.tableData.total = res.data.count || 0
          this.listLoading = false
        })
        .catch(res => {
          this.listLoading = false
          this.$message.error(res.message || '获取排班列表失败')
        })
    },
    
    // 打开添加排班弹窗
    openAddModal() {
      this.dialogTitle = '添加排班'
      this.formData = {
        id: 0,
        staff_id: '',
        service_id: '',
        start_time: '',
        end_time: '',
        num: 1,
        date: '',
        arrage_time_list: '',
        week_days: [], 
        end_date: ''
      }
      this.batchMode = false 
      this.dialogVisible = true
    },
    
    // 补充缺失的方法
    // 编辑排班
    handleEdit(row) {
      this.dialogTitle = '编辑排班'
      this.formData = { ...row }
      // 修复日期格式问题
      if (this.formData.date && typeof this.formData.date === 'number') {
        this.formData.date = this.formatDate(this.formData.date)
      }
      this.batchMode = false // 编辑模式下不显示批量创建
      this.dialogVisible = true
    },
    
    // 关闭弹窗
    handleDialogClose() {
      this.dialogVisible = false
      this.$refs.formValidate.resetFields()
    },
    
    // 批量模式变更处理
    handleBatchModeChange(val) {
      if (val) {
        // 确保使用数字而不是字符串
        this.$set(this.formData, 'week_days', [1, 2, 3, 4, 5]);
        
        // 默认结束日期为一周后
        const date = this.formData.date ? new Date(this.formData.date) : new Date();
        date.setDate(date.getDate() + 7);
        this.formData.end_date = this.formatDateToString(date);
      } else {
        this.$set(this.formData, 'week_days', []);
        this.formData.end_date = '';
      }
    },
    
    // 提交表单
    handleSubmit() {
      this.$refs.formValidate.validate(valid => {
        if (valid) {
          this.submitLoading = true
          
          // 准备提交的数据
          const data = JSON.parse(JSON.stringify(this.formData));
          
          // 确保 week_days 是数组
          if (this.batchMode && !data.id) {
            if (!Array.isArray(data.week_days)) {
              if (data.week_days) {
                data.week_days = [parseInt(data.week_days)];
              } else {
                data.week_days = [];
              }
            } else {
              // 确保数组中的值是数字
              data.week_days = data.week_days.map(day => parseInt(day));
            }
          } else {
            // 如果不是批量模式，删除这些字段
            delete data.week_days;
            delete data.end_date;
          }
          
          // 判断是新增还是编辑
          const request = data.id ? updateArrange(data.id, data) : saveArrange(data)
          request.then(res => {
            this.$message.success(data.id ? '编辑成功' : '添加成功')
            this.dialogVisible = false
            this.getList()
            this.$refs.formValidate.resetFields()
            this.submitLoading = false
          }).catch(res => {
            this.submitLoading = false
            this.$message.error(res.message)
          })
        }
      })
    },
    
    // 删除排班
    handleDelete(id) {
      this.$modalSure('确定要删除该排班吗？').then(() => {
        deleteArrange(id)
          .then(res => {
            this.$message.success(res.message || '删除成功')
            this.getList()
          })
          .catch(res => {
            this.$message.error(res.message)
          })
      })
    },
    
    // 处理表格选择变化
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    
    // 批量删除
    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选择要删除的排班');
        return;
      }
      
      const ids = this.selectedRows.map(row => row.id);
      
      this.$modalSure(`确定要删除选中的${ids.length}条排班吗？`).then(() => {
        batchDeleteArrange(ids)
          .then(res => {
            this.$message.success(res.message || '批量删除成功');
            this.getList();
            this.selectedRows = [];
          })
          .catch(res => {
            this.$message.error(res.message);
          });
      });
    },
    
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex
    },
    
    closeEdit() {
      this.tabClickIndex = null
    },
    
    pageChange(page) {
      this.tableFrom.page = page
      this.getList()
    },
    
    handleSizeChange(val) {
      this.tableFrom.limit = val
      this.getList()
    },
    
    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      if (typeof date === 'string') return date
      
      const d = new Date(date * 1000)
      const year = d.getFullYear()
      const month = (d.getMonth() + 1).toString().padStart(2, '0')
      const day = d.getDate().toString().padStart(2, '0')
      
      return `${year}-${month}-${day}`
    },
    
    formatDateToString(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  }
}
</script>

<style scoped lang="scss">
.divBox {
  padding: 10px;
}

.selWidth {
  width: 300px !important;
}

.block {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.mr10 {
  margin-right: 10px;
}

.header-buttons {
  display: flex;
  gap: 10px;
}
.header-buttons {
  display: flex;
  gap: 10px;
}
</style>